package com.penjin.android.message.company;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;

import com.easemob.chat.EMChatManager;
import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.penjin.android.R;
import com.penjin.android.activity.geren.GerenInfoActivity;
import com.penjin.android.constants.HttpConstants;
import com.penjin.android.domain.PenjinCompany;
import com.penjin.android.domain.PenjinDepartment;
import com.penjin.android.domain.PenjinEaseUser;
import com.penjin.android.domain.PenjinUser;
import com.penjin.android.http.HttpService;
import com.penjin.android.message.EMChatHelper;
import com.penjin.android.message.contact.EMContactDetailActivity;
import com.penjin.android.message.domain.EaseUser;
import com.penjin.android.message.utils.EaseConstant;
import com.penjin.android.service.UserService;
import com.penjin.android.utils.HttpUtil;
import com.penjin.android.utils.ToastHelper;
import com.penjin.android.view.CustomProgressDialog;
import com.penjin.android.view.TitleBarView;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 显示绑定企业之后的企业分组
 * <p/>
 * Created by Administrator on 2016/3/11.
 */
public class ShowCompanyStaffActivity extends Activity {

    HttpService httpService;
    TextHttpResponseHandler getCompanyStaffsHandler;
    RequestHandle requestHandle;
    TitleBarView titleBarView;
    CustomProgressDialog progressDialog;
    Boolean isLoaded = false;
    PenjinCompany company;
    ExpandableListView expanded_menu;
    CompanyStaffAdapter adapter;
    ExpandableListView.OnChildClickListener childClickListener;
    ExpandableListView.OnGroupClickListener groupClickListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_activiti_show_company_staff);
        initData(savedInstanceState);
        initView();
        initListener();
        initHttp();
    }

    private void initView() {
        titleBarView = (TitleBarView) findViewById(R.id.titleBarView);
        titleBarView.setTitleBarListener(new TitleBarView.TitleBarListener() {
            @Override
            public void left(View view) {
                ShowCompanyStaffActivity.this.finish();
            }

            @Override
            public void center(View view) {

            }

            @Override
            public void right(View view) {

            }
        });
        progressDialog = CustomProgressDialog.createDialog(this);
        progressDialog.setMessage("请稍后...");
        expanded_menu = (ExpandableListView) findViewById(R.id.expanded_menu);
        adapter = new CompanyStaffAdapter(this, null, null);
        expanded_menu.setAdapter(adapter);
    }

    private void initListener() {
        childClickListener = new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                //判断是否是环信好友
                PenjinEaseUser listItem = (PenjinEaseUser) adapter.getChild(groupPosition, childPosition);
                String easeUsername = listItem.getUsername();
                EaseUser easeUser = EMChatHelper.getInstance().getUserInfo(easeUsername);
                if (easeUser == null) {
                    ToastHelper.showMessage("还不是您的好友", ShowCompanyStaffActivity.this);
                } else if(easeUsername.equals(UserService.getInstance(ShowCompanyStaffActivity.this).getCurrentUser().getPhone())) {
                    //显示自己
                    Intent intent=new Intent(ShowCompanyStaffActivity.this, GerenInfoActivity.class);
                    startActivity(intent);
                }else{//好友聊天
                    Intent intent = new Intent(ShowCompanyStaffActivity.this, EMContactDetailActivity.class);
                    intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
                    intent.putExtra(EaseConstant.EXTRA_USER_ID, easeUser.getUsername());
                    startActivity(intent);
                }
                return false;
            }
        };
        groupClickListener = new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return false;
            }
        };
        this.expanded_menu.setOnChildClickListener(childClickListener);
    }

    private void initData(Bundle savedInstance) {
        company = UserService.getInstance(this.getApplicationContext()).getCurrentCompany();
    }

    private void initHttp() {
        this.httpService = HttpService.getInstance(this.getApplicationContext());
        this.getCompanyStaffsHandler = new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                progressDialog.dismiss();
                if (s != null) {
                    System.out.println(s);
                }
                ToastHelper.showServerError(ShowCompanyStaffActivity.this);
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                progressDialog.dismiss();
                System.out.println(s);
                isLoaded = true;
                try {
                    JSONObject jo = new JSONObject(s);
                    boolean result = jo.optBoolean("result");
                    if (result) {
                        List<PenjinDepartment> departmentList = new ArrayList();
                        List<List<PenjinEaseUser>> staffLists = new ArrayList<>();
                        JSONArray jsonArray = jo.optJSONArray("data");
                        JSONObject entity;
                        Random random=new Random();
                        for (int j = 0; j < jsonArray.length(); j++) {
                            entity = jsonArray.getJSONObject(j);
                            PenjinDepartment department = new PenjinDepartment();
                            department.setDepartmentName(entity.optString("department"));
                            JSONArray persons = entity.optJSONArray("person");
                            if(persons.length()>0){
                                //添加部门
                                departmentList.add(department);
                                //添加员工
                                List<PenjinEaseUser> staffList = new ArrayList<>();
                                department.setDepartmentStaffNum(persons.length());
                                JSONObject person;
                                for (int m = 0; m < persons.length(); m++) {
                                    person = persons.optJSONObject(m);
                                    PenjinEaseUser staff = new PenjinEaseUser(person.optString("username"));
                                    staff.setAvatar(person.optString("head_url"));
                                    staff.setSex(person.optString("gender"));
                                    staff.setNick(person.optString("nickname"));
                                    staff.setRealname(person.optString("realname"));
                                    staff.setPosition(person.optString("position"));
                                    staff.colorIndex=random.nextInt(11);
                                    staffList.add(staff);
                                }
                                staffLists.add(staffList);
                            }
                        }
                        adapter.setData(departmentList, staffLists);
                        adapter.notifyDataSetChanged();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastHelper.showJsonError(ShowCompanyStaffActivity.this);
                }
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isLoaded) {
            if (HttpUtil.isNetworkAvailable(this)) {
                try {
                    RequestParams params = new RequestParams();
                    System.out.println(company.getCompanyId());
                    params.put("companyId", company.getCompanyId());
                    this.httpService.postRequestWithHandle(this.getApplicationContext(), HttpConstants.HOST + HttpConstants.AppCompanyFriend, params, this.getCompanyStaffsHandler);
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastHelper.showConnectionError(this);
                }
            } else {
                ToastHelper.showNoNetwork(this);
            }

        }
    }

    @Override
    protected void onDestroy() {
        if (requestHandle != null) {
            requestHandle.cancel(true);
        }
        super.onDestroy();
    }
}
